const finance = require('../../../utils/finance');

Page({
  data: {
    list: [],
    current: 1,
    size: 3,
    total: 0,
    loading: false,
    finished: false,
    isScrolling: false,
    scrollTop: 0,
    viewportHeight: 0
  },

  scrollTimer: null,
  visibleImages: new Set(),
  lastTapTime: 0,
  tapTimeout: null,

  onLoad(options) {
    console.log('gallery.js onLoad', options);
    this.initViewport();
    this.refreshFirstPage();
  },

  initViewport() {
    const systemInfo = wx.getSystemInfoSync();
    this.setData({
      viewportHeight: systemInfo.windowHeight
    });
  },

  async refreshFirstPage() {
    console.log('刷新第一页');
    this.setData({ current: 1, finished: false });
    await this.loadPage(true);
  },

  async loadPage(replace = false) {
    if (this.data.loading || this.data.finished) return;
    this.setData({ loading: true });
    try {
      let res = await finance.galleryPageList(this.data.current, this.data.size);
      const weekdayMap = ['周日','周一','周二','周三','周四','周五','周六'];
      const arr = Array.isArray(res.records) ? res.records : [];
      let prevMonthKey = replace ? null : (this.data.list && this.data.list.length > 0 ? this.data.list[this.data.list.length - 1].monthKey : null);
      const records = [];
      
      arr.forEach(rec => {
        const gallery = Array.isArray(rec.gallery) ? rec.gallery : [];
        const images = gallery.filter(g => (g.mediaType || 'image') === 'image');
        const audios = gallery.filter(g => (g.mediaType || '') === 'audio');
        
        let dayNum = '', monthStr = '', weekdayStr = '', monthKey = '', monthTitle = '';
        try {
          const dateStr = rec.date || rec.day || '';
          const dt = new Date(dateStr.replace(/-/g,'/'));
          const m = String(dt.getMonth()+1).padStart(2,'0');
          const y = String(dt.getFullYear());
          const d = String(dt.getDate()).padStart(2,'0');
          dayNum = d;
          monthStr = `${m}月`;
          weekdayStr = weekdayMap[dt.getDay()];
          monthKey = `${y}-${m}`;
          monthTitle = `${y}年${m}月`;
        } catch (_) {}
        
        const left = [], right = [];
        images.forEach((img, idx) => { 
          const imgWithState = {
            ...img,
            loaded: false,
            shouldLoad: false,
            loading: false
          };
          if (idx % 2 === 0) left.push(imgWithState); 
          else right.push(imgWithState); 
        });
        
        const showMonthHeader = monthKey && monthKey !== prevMonthKey;
        if (monthKey) prevMonthKey = monthKey;
        
        const recordData = {
          id: rec.day,
          ...rec,
          previewUrls: images.map(g => g.resourceUrl).filter(url => url && typeof url === 'string' && url.trim().length > 0),
          dayNum,
          monthStr,
          weekdayStr,
          monthKey,
          monthTitle,
          showMonthHeader,
          left,
          right,
          audios
        };
        console.log('创建记录数据:', recordData.id, '图片数量:', images.length, '有效预览URLs:', recordData.previewUrls.length, '左列:', left.length, '右列:', right.length);
        records.push(recordData);
      });
      
      const merged = replace ? records : (this.data.list || []).concat(records);
      const finished = merged.length >= (res.total || 0) || records.length === 0;
      
      const allImageUrls = [];
      merged.forEach(item => {
        // 按照页面显示顺序收集图片：左列和右列交替
        const leftImages = item.left || [];
        const rightImages = item.right || [];
        const maxLength = Math.max(leftImages.length, rightImages.length);
        
        for (let i = 0; i < maxLength; i++) {
          // 先添加左列图片
          if (i < leftImages.length && leftImages[i].resourceUrl) {
            const url = leftImages[i].resourceUrl;
            if (url && typeof url === 'string' && url.trim().length > 0 && !allImageUrls.includes(url)) {
              allImageUrls.push(url);
            }
          }
          // 再添加右列图片
          if (i < rightImages.length && rightImages[i].resourceUrl) {
            const url = rightImages[i].resourceUrl;
            if (url && typeof url === 'string' && url.trim().length > 0 && !allImageUrls.includes(url)) {
              allImageUrls.push(url);
            }
          }
        }
      });
      
      merged.forEach(item => {
        item.allPreviewUrls = allImageUrls;
      });
      
      console.log('设置数据:', {
        记录数量: merged.length,
        全局图片URLs数量: allImageUrls.length,
        前5个URLs: allImageUrls.slice(0, 5),
        最后5个URLs: allImageUrls.slice(-5)
      });

      this.setData({
        list: merged,
        total: res.total || 0,
        loading: false,
        finished,
        allImageUrls
      });

          setTimeout(() => {
        console.log('数据加载完成，开始计算可视区域');
        this.calculateVisibleImages();
        setTimeout(() => {
          this.loadVisibleImages();
        }, 200);
      }, 300);
    } catch (e) {
      console.error('异常啦：', e);
      this.setData({ loading: false });
    }
  },

  onReachBottom() {
    console.log('触发上拉加载更多');
    if (this.data.finished || this.data.loading) return;
    
    if (this.loadMoreTimer) {
      clearTimeout(this.loadMoreTimer);
    }
    
    this.loadMoreTimer = setTimeout(async () => {
      this.setData({ current: this.data.current + 1 }, async () => {
        console.log(`加载第${this.data.current}页数据`);
        await this.loadPage(false);
      });
    }, 100);
  },

  async onPullDownRefresh() {
    await this.refreshFirstPage();
    wx.stopPullDownRefresh();
  },

  onScrollStart() {
    if (!this.data.isScrolling) {
      this.setData({ isScrolling: true });
      console.log('开始滑动，暂停图片加载');
    }
  },

  onScroll(e) {
    const { scrollTop } = e.detail;
    const scrollDiff = Math.abs(scrollTop - (this.data.scrollTop || 0));
    
    if (scrollDiff > 10) {
      this.setData({
        scrollTop,
        isScrolling: true
      });
    }

    if (this.scrollTimer) {
      clearTimeout(this.scrollTimer);
    }

    const waitTime = scrollDiff > 100 ? 300 : 150;
    this.scrollTimer = setTimeout(() => {
      this.onScrollEnd();
    }, waitTime);
  },

  onScrollEnd() {
    console.log('滑动停止，恢复图片加载');
    this.setData({ isScrolling: false });
    this.calculateVisibleImages();
    setTimeout(() => {
      this.loadVisibleImages();
    }, 100);
  },

  calculateVisibleImages() {
    const { list } = this.data;
    console.log('开始计算可视区域，列表长度:', list.length);
    this.visibleImages.clear();

    if (!list || list.length === 0) {
      console.log('列表为空，跳过计算');
      return;
    }

    const query = this.createSelectorQuery();
    query.selectViewport().scrollOffset();
    query.selectAll('.timeline-item').boundingClientRect();
    
    query.exec((res) => {
      const scrollInfo = res[0];
      const rects = res[1];
      
      if (!scrollInfo || !rects) {
        console.warn('无法获取滚动信息或元素位置');
        this.loadFallbackImages();
        return;
      }

      const { scrollTop } = scrollInfo;
      const viewportHeight = this.data.viewportHeight;
      
      console.log('DOM查询结果:', { scrollTop, viewportHeight, elementsCount: rects.length });

      rects.forEach((rect, index) => {
        if (!rect) return;
        
        const { top, bottom } = rect;
        const isVisible = (bottom > 0 && top < viewportHeight);
        
        if (isVisible && index < list.length) {
          const record = list[index];
          if (record) {
            if (record.left) {
              record.left.forEach(img => {
                this.visibleImages.add(img.id);
              });
            }
            if (record.right) {
              record.right.forEach(img => {
                this.visibleImages.add(img.id);
              });
            }
            console.log('记录在可视区域:', index, '图片数量:', (record.left?.length || 0) + (record.right?.length || 0));
          }
        }
      });

      console.log('DOM查询计算出的可视区域图片数量:', this.visibleImages.size);
      
      if (this.visibleImages.size === 0) {
        console.log('DOM查询未找到可视图片，使用降级方案');
        this.loadFallbackImages();
      }
    });
  },

  loadFallbackImages() {
    const { list } = this.data;
    const loadCount = Math.min(5, list.length);
    
    console.log('使用降级方案，加载前', loadCount, '条记录');
    
    for (let i = 0; i < loadCount; i++) {
      const record = list[i];
      if (record) {
        if (record.left) {
          record.left.forEach(img => {
            this.visibleImages.add(img.id);
          });
        }
        if (record.right) {
          record.right.forEach(img => {
            this.visibleImages.add(img.id);
          });
        }
      }
    }
    
    console.log('降级方案加载的图片数量:', this.visibleImages.size);
  },





  loadVisibleImages() {
    if (this.data.isScrolling) {
      console.log('正在滑动中，跳过图片加载');
      return;
    }

    console.log('开始加载可视区域图片，数量:', this.visibleImages.size);
    
    if (this.visibleImages.size === 0) {
      console.warn('可视区域图片数量为0，可能计算有误');
      return;
    }

    let loadCount = 0;
    this.visibleImages.forEach(imgId => {
      const loaded = this.loadImageById(imgId);
      if (loaded) loadCount++;
    });
    
    console.log('实际触发加载的图片数量:', loadCount);
  },

  loadImageById(imgId) {
    const list = [...this.data.list];
    let updated = false;

    for (let recordIndex = 0; recordIndex < list.length; recordIndex++) {
      const record = { ...list[recordIndex] };

      if (record.left) {
        const leftIndex = record.left.findIndex(img => img.id === imgId);
        if (leftIndex !== -1 && !record.left[leftIndex].loaded) {
          if (!record.left[leftIndex].shouldLoad) {
            record.left = [...record.left];
            record.left[leftIndex] = { ...record.left[leftIndex], shouldLoad: true, loading: true };
            console.log('设置左列图片状态:', imgId, {
              id: record.left[leftIndex].id,
              resourceUrl: record.left[leftIndex].resourceUrl,
              shouldLoad: record.left[leftIndex].shouldLoad,
              loading: record.left[leftIndex].loading,
              loaded: record.left[leftIndex].loaded
            });
            
            // 检查图片URL是否有效
            if (!record.left[leftIndex].resourceUrl) {
              console.error('左列图片URL为空:', imgId);
            }
            
            // 设置超时，如果10秒后还没加载完成，重置loading状态
            setTimeout(() => {
              this.resetImageLoadingState(imgId, record.id);
            }, 10000);
            list[recordIndex] = record;
            updated = true;
            console.log('标记左列图片开始加载:', imgId);
            break;
          } else {
            console.log('左列图片已标记加载:', imgId);
            return true;
          }
        }
      }

      if (record.right) {
        const rightIndex = record.right.findIndex(img => img.id === imgId);
        if (rightIndex !== -1 && !record.right[rightIndex].loaded) {
          if (!record.right[rightIndex].shouldLoad) {
            record.right = [...record.right];
            record.right[rightIndex] = { ...record.right[rightIndex], shouldLoad: true, loading: true };
            console.log('设置右列图片状态:', imgId, {
              id: record.right[rightIndex].id,
              resourceUrl: record.right[rightIndex].resourceUrl,
              shouldLoad: record.right[rightIndex].shouldLoad,
              loading: record.right[rightIndex].loading,
              loaded: record.right[rightIndex].loaded
            });
            
            // 检查图片URL是否有效
            if (!record.right[rightIndex].resourceUrl) {
              console.error('右列图片URL为空:', imgId);
            }
            
            // 设置超时，如果10秒后还没加载完成，重置loading状态
            setTimeout(() => {
              this.resetImageLoadingState(imgId, record.id);
            }, 10000);
            list[recordIndex] = record;
            updated = true;
            console.log('标记右列图片开始加载:', imgId);
            break;
          } else {
            console.log('右列图片已标记加载:', imgId);
            return true;
          }
        }
      }
    }

    if (updated) {
      this.setData({ list });
      return true;
    }
    
    console.log('未找到图片或图片已加载完成:', imgId);
    return false;
  },

  // 重置图片加载状态（超时处理）
  resetImageLoadingState(imgId, recordId) {
    const list = [...this.data.list];
    const recordIndex = list.findIndex(item => item.id === recordId);
    
    if (recordIndex !== -1) {
      const record = { ...list[recordIndex] };
      let updated = false;
      
      // 检查左列
      if (record.left) {
        const leftIndex = record.left.findIndex(img => img.id === imgId);
        if (leftIndex !== -1 && record.left[leftIndex].loading && !record.left[leftIndex].loaded) {
          record.left = [...record.left];
          record.left[leftIndex] = { ...record.left[leftIndex], loading: false };
          updated = true;
          console.log('重置左列图片loading状态:', imgId);
        }
      }
      
      // 检查右列
      if (record.right) {
        const rightIndex = record.right.findIndex(img => img.id === imgId);
        if (rightIndex !== -1 && record.right[rightIndex].loading && !record.right[rightIndex].loaded) {
          record.right = [...record.right];
          record.right[rightIndex] = { ...record.right[rightIndex], loading: false };
          updated = true;
          console.log('重置右列图片loading状态:', imgId);
        }
      }
      
      if (updated) {
        list[recordIndex] = record;
        this.setData({ list });
      }
    }
  },

  onTapImage(e) {
    // 防抖：防止短时间内重复点击
    const now = Date.now();
    if (this.lastTapTime && (now - this.lastTapTime) < 1000) {
      console.log('点击过于频繁，忽略本次点击');
      return false;
    }
    this.lastTapTime = now;

    // 延迟执行，避免与双击事件冲突
    if (this.tapTimeout) {
      clearTimeout(this.tapTimeout);
    }
    
    const { urls, current, recordid, imgid } = e.currentTarget.dataset;
    
    this.tapTimeout = setTimeout(() => {
      this.handleImagePreview({ urls, current, recordid, imgid });
    }, 300); // 300ms延迟，如果期间有双击则取消单击
    
    return false;
  },

  // 处理图片预览的实际逻辑
  handleImagePreview({ urls, current, recordid, imgid }) {
    console.log('执行图片预览:', { urls, current, recordid, imgid, allImageUrls: this.data.allImageUrls });

    // 优先使用全局图片URLs，确保顺序正确
    let previewUrls = [];
    
    if (this.data.allImageUrls && this.data.allImageUrls.length > 0) {
      // 过滤掉无效的URL
      previewUrls = this.data.allImageUrls.filter(url => url && typeof url === 'string' && url.trim().length > 0);
      console.log('使用全局预览URLs:', previewUrls.length);
    } else if (Array.isArray(urls) && urls.length > 0) {
      // 降级使用记录的URLs
      previewUrls = urls.filter(url => url && typeof url === 'string' && url.trim().length > 0);
      console.log('使用记录的预览URLs:', previewUrls.length);
    } else {
      console.warn('没有找到可预览的图片URLs');
      wx.showToast({
        title: '图片加载中，请稍后',
        icon: 'none'
      });
      return;
    }

    if (previewUrls.length === 0) {
      console.warn('过滤后没有有效的图片URLs');
      wx.showToast({
        title: '没有可预览的图片',
        icon: 'none'
      });
      return;
    }

    // 确保current URL有效
    let currentUrl = current;
    if (!currentUrl || typeof currentUrl !== 'string' || currentUrl.trim().length === 0) {
      console.warn('当前图片URL无效:', currentUrl);
      currentUrl = previewUrls[0];
    }

    // 检查current URL是否在预览数组中
    const currentIndex = previewUrls.indexOf(currentUrl);
    if (currentIndex === -1) {
      console.warn('当前图片URL不在预览数组中:', currentUrl);
      console.log('预览数组:', previewUrls);
      // 尝试找到相似的URL或使用第一张
      currentUrl = previewUrls[0];
    }

    this._isPreviewingImage = true;
    
    console.log('开始预览图片:', { 
      预览数组长度: previewUrls.length, 
      当前图片: currentUrl,
      当前索引: previewUrls.indexOf(currentUrl),
      前3个URLs: previewUrls.slice(0, 3)
    });

    // 优化：限制预览图片数量，提高加载成功率
    const maxPreviewCount = 20; // 最多预览20张图片
    let finalPreviewUrls = previewUrls;
    let finalCurrentUrl = currentUrl;
    
    if (previewUrls.length > maxPreviewCount) {
      // 找到当前图片的索引
      const currentIndex = previewUrls.indexOf(currentUrl);
      
      if (currentIndex !== -1) {
        // 以当前图片为中心，取前后各10张
        const startIndex = Math.max(0, currentIndex - 10);
        const endIndex = Math.min(previewUrls.length, currentIndex + 11);
        finalPreviewUrls = previewUrls.slice(startIndex, endIndex);
        finalCurrentUrl = currentUrl; // 当前图片保持不变
        
        console.log(`优化预览数量: ${previewUrls.length} -> ${finalPreviewUrls.length}, 当前图片索引: ${currentIndex} -> ${finalPreviewUrls.indexOf(currentUrl)}`);
      } else {
        // 如果找不到当前图片，就取前20张
        finalPreviewUrls = previewUrls.slice(0, maxPreviewCount);
        finalCurrentUrl = finalPreviewUrls[0];
        console.log(`当前图片不在数组中，使用前${maxPreviewCount}张图片`);
      }
    }

    // 检查网络状态
    wx.getNetworkType({
      success: (res) => {
        console.log('当前网络类型:', res.networkType);
        if (res.networkType === 'none') {
          wx.showToast({
            title: '网络连接异常',
            icon: 'none'
          });
          return;
        }
      }
    });

    console.log('最终预览参数:', {
      图片数量: finalPreviewUrls.length,
      当前图片: finalCurrentUrl?.substring(0, 50) + '...',
      当前索引: finalPreviewUrls.indexOf(finalCurrentUrl)
    });

    // 详细记录前几个图片URL用于调试
    console.log('前5个图片URL:');
    finalPreviewUrls.slice(0, 5).forEach((url, index) => {
      console.log(`${index + 1}. ${url}`);
    });

    // 检查图片域名是否在小程序白名单中
    const imageHosts = [...new Set(finalPreviewUrls.map(url => {
      try {
        return new URL(url).hostname;
      } catch (e) {
        return 'invalid-url';
      }
    }))];
    console.log('图片域名列表:', imageHosts);



    wx.previewImage({
      urls: finalPreviewUrls,
      current: finalCurrentUrl,
      success: () => {
        console.log('图片预览成功');
      },
      fail: (err) => {
        console.error('图片预览失败:', err);
        console.log('失败的参数:', { urls: finalPreviewUrls, current: finalCurrentUrl });
        
        // 如果预览失败，尝试只预览当前图片
        if (finalCurrentUrl) {
          console.log('尝试只预览当前图片...');
          wx.previewImage({
            urls: [finalCurrentUrl],
            current: finalCurrentUrl,
            success: () => {
              console.log('单图片预览成功');
            },
            fail: (err2) => {
              console.error('单图片预览也失败:', err2);
              
              // 最后的尝试：提供复制链接的选项
              wx.showModal({
                title: '图片加载失败',
                content: '图片无法加载，是否复制图片链接到剪贴板？',
                confirmText: '复制链接',
                cancelText: '取消',
                success: (modalRes) => {
                  if (modalRes.confirm) {
                    wx.setClipboardData({
                      data: finalCurrentUrl,
                      success: () => {
                        wx.showToast({
                          title: '链接已复制',
                          icon: 'success'
                        });
                      }
                    });
                  }
                }
              });
            }
          });
        } else {
          wx.showToast({
            title: '图片预览失败',
            icon: 'none'
          });
        }
      }
    });
  },

  onDoubleTapImage(e) {
    // 取消单击的延迟执行
    if (this.tapTimeout) {
      clearTimeout(this.tapTimeout);
      this.tapTimeout = null;
    }
    
    const { recordid } = e.currentTarget.dataset;
    console.log('双击图片，显示操作菜单:', recordid);
    
    if (!recordid) return;

    wx.showActionSheet({
      itemList: ['查看记账'],
      success: (res) => {
        if (res.tapIndex === 0) {
          wx.navigateTo({
            url: `/pages/finance/write/write?id=${recordid}`
          });
        }
      }
    });
  },

  onImageLoad(e) {
    const { imgid, recordid } = e.currentTarget.dataset;
    console.log('图片加载成功回调触发:', imgid, recordid);
    
    if (!imgid || !recordid) {
      console.warn('图片加载成功但缺少必要参数:', { imgid, recordid });
      return;
    }

    const list = [...this.data.list];
    const recordIndex = list.findIndex(item => item.id === recordid);
    
    if (recordIndex !== -1) {
      const record = { ...list[recordIndex] };
      let updated = false;
      
      if (record.left) {
        const leftIndex = record.left.findIndex(img => img.id === imgid);
        if (leftIndex !== -1) {
          record.left = [...record.left];
          record.left[leftIndex] = { 
            ...record.left[leftIndex], 
            loaded: true, 
            loading: false,
            shouldLoad: true 
          };
          updated = true;
          console.log('更新左列图片状态:', imgid);
        }
      }
      
      if (record.right) {
        const rightIndex = record.right.findIndex(img => img.id === imgid);
        if (rightIndex !== -1) {
          record.right = [...record.right];
          record.right[rightIndex] = { 
            ...record.right[rightIndex], 
            loaded: true, 
            loading: false,
            shouldLoad: true 
          };
          updated = true;
          console.log('更新右列图片状态:', imgid);
        }
      }
      
      if (updated) {
        list[recordIndex] = record;
        this.setData({ list });
      }
    } else {
      console.warn('找不到对应的记录:', recordid);
    }
  },

  onImageError(e) {
    const { imgid, recordid } = e.currentTarget.dataset;
    console.warn('图片加载失败:', imgid, recordid);
    
    if (!imgid || !recordid) {
      console.warn('图片加载失败但缺少必要参数:', { imgid, recordid });
      return;
    }
    
    const list = [...this.data.list];
    const recordIndex = list.findIndex(item => item.id === recordid);
    
    if (recordIndex !== -1) {
      const record = { ...list[recordIndex] };
      let updated = false;
      
      if (record.left) {
        const leftIndex = record.left.findIndex(img => img.id === imgid);
        if (leftIndex !== -1) {
          record.left = [...record.left];
          record.left[leftIndex] = { 
            ...record.left[leftIndex], 
            loaded: false, 
            error: true, 
            loading: false,
            shouldLoad: true 
          };
          updated = true;
        }
      }
      
      if (record.right) {
        const rightIndex = record.right.findIndex(img => img.id === imgid);
        if (rightIndex !== -1) {
          record.right = [...record.right];
          record.right[rightIndex] = { 
            ...record.right[rightIndex], 
            loaded: false, 
            error: true, 
            loading: false,
            shouldLoad: true 
          };
          updated = true;
        }
      }
      
      if (updated) {
        list[recordIndex] = record;
        this.setData({ list });
      }
    }
  },

  onShow() {
    console.log('gallery.js onShow, isPreviewingImage:', this._isPreviewingImage);
    if (this._cameBack && !this._isPreviewingImage) {
      this.refreshFirstPage();
      this._cameBack = false;
    }
    this._isPreviewingImage = false;
    
    setTimeout(() => {
      console.log('页面显示，重新计算可视区域');
      this.calculateVisibleImages();
      setTimeout(() => {
        this.loadVisibleImages();
      }, 200);
    }, 200);
  },

  onHide() {
    this._cameBack = true;
  },

  onUnload() {
    console.log('页面被关闭了');
    this.setData({ list: [], total: 0, current: 1, finished: false });

    if (this.loadMoreTimer) {
      clearTimeout(this.loadMoreTimer);
    }
    if (this.scrollTimer) {
      clearTimeout(this.scrollTimer);
    }
    if (this.tapTimeout) {
      clearTimeout(this.tapTimeout);
    }

    this.visibleImages.clear();
  },


});